package ru.testtask.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.support.AbstractMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import ru.testtask.model.XmlDocument;
import ru.testtask.service.XmlService;
import ru.testtask.util.XmlParseException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

@Controller
public class AppWebController {

    private static final Log logger = LogFactory.getLog(AppWebController.class);

    private final XmlService xmlService;
    private final AbstractMessageSource messageSource;

    public AppWebController(@Qualifier("xmlService") XmlService xmlService,
                            @Qualifier("messageSource") AbstractMessageSource messageSource) {
        this.xmlService = xmlService;
        this.messageSource = messageSource;
    }

    @RequestMapping(value = "/main.html")
    public ModelAndView getMainView(String error) {
        ModelAndView mv = new ModelAndView("main");
        mv.addObject("existingDocuments", xmlService.getDocumentsList());
        mv.addObject("error_msg", error);
        return mv;
    }

    @RequestMapping(value = "/downloadxml.html")
    public ModelAndView downloadXml(int docId, HttpServletResponse response) {
        XmlDocument xmlDoc = xmlService.readObjectModel(docId);
        if (xmlDoc != null) {
            response.setHeader("Content-Type", "text/xml;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + xmlDoc.getName());
            return new ModelAndView("xmlDocument", "xmlDoc", xmlService.transformObjectModelToXmlString(xmlDoc));
        }
        return null;
    }

    @RequestMapping(value = "/uploadxml.html")
    public ModelAndView uploadXml(UploadFormBean formBean) throws IOException {

        MultipartFile xmlDocFile = formBean.getXmlDocFile();

        if (xmlDocFile == null) {
            return getMainView(messageSource.getMessage("field.required", null, Locale.getDefault()));
        }
        String xml = new String(xmlDocFile.getBytes(), "UTF8");
        String name = xmlDocFile.getOriginalFilename();
        if (!StringUtils.hasText(name)) {
            return getMainView(messageSource.getMessage("field.required", null, Locale.getDefault()));
        }
        String error = null;
        try {
            XmlDocument doc = xmlService.transformXmlStringToObjectModel(name, xml);
            xmlService.saveObjectModel(doc);
        } catch (XmlParseException e) {
            error = messageSource.getMessage("parsing.error", new Object[] {e.getMessage()}, e.getMessage(), Locale.getDefault());
            logger.info(e);
        } catch (Exception e) {
            error = messageSource.getMessage("db.error", null, Locale.getDefault());
            logger.info(e);
        }
        return getMainView(error);

    }

}
